package org.example.ams.log;

import cn.hutool.json.JSONUtil;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.example.ams.entity.system.SysLog;
import org.example.ams.service.system.ISysLogService;
import org.example.ams.util.SpringMvcUtils;
import org.example.common.api.CommonResult;
import org.example.common.utils.IpUtils;
import org.example.security.util.LoginUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Date;

/**
 * 日志切面
 */
@Component
@Aspect
public class LogAspect {

    @Autowired
    private ISysLogService sysLogService;

    /**
     * 定义日志切入点
     */
    @Pointcut("@annotation(org.example.ams.log.Log)")
    public void logPointcut() {
    }

    /**
     * 定义通知
     * @param joinPoint 切点
     * @param rvt 切点方法返回值
     */
    @AfterReturning(returning = "rvt",value = "logPointcut()")
    public void saveLog(JoinPoint joinPoint,Object rvt) {
        CommonResult<Object> commonResult = (CommonResult<Object>) rvt;
        if (commonResult.getCode() == 200) {
            // 获取切点方法
            MethodSignature signature = (MethodSignature) joinPoint.getSignature();
            Method method = signature.getMethod();
            // 获取方法上的注解
            Log log = method.getAnnotation(Log.class);
            if (log != null) {
                // 封装日志对象
                SysLog sysLog = new SysLog();
                sysLog.setUser(LoginUtils.currentLoginUser().getUsername());
                sysLog.setOptionTime(new Date());
                sysLog.setIp(SpringMvcUtils.getRequest().getRemoteAddr());
                sysLog.setContent(log.value());
                // 判断是否记录参数，如果记录，序列化参数
                if (log.ifRecordParam() == 1) {
                    // 获取切点方法的参数
                    Object[] args = joinPoint.getArgs();
                    sysLog.setParam(JSONUtil.toJsonStr(args));
                }
                sysLogService.save(sysLog);
            }
        }
    }
}
